package com.monitor.display_platform.business.thread.v2.th;

import com.monitor.display_platform.business.thread.v2.Cycle;
import com.monitor.display_platform.business.thread.v2.Observable;
import com.monitor.display_platform.business.thread.v2.TaskFuture;
import com.monitor.display_platform.business.thread.v2.TaskLifeCycle;
import javafx.concurrent.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static java.lang.Thread.currentThread;

public class OneConsumer<T>  implements Runnable, Observable {

    private static final Logger log = LoggerFactory.getLogger(OneConsumer.class);
    private int i = 2;

    @Override
    public void run() {
        log.info("start first consumer");
        this.update(Cycle.STARTED, null, null);
        try {
            this.update(Cycle.RUNNING, null, null);
            while(true){
                if (i == 10){
                    throw new IllegalArgumentException("参数异常。。。。。。。。。。。。。。。。。。");
                }
                Thread.sleep(1000);
                i ++;
            }
//            T result = this.task.call();
//            this.update(Cycle.DONE, result, null);
        } catch (Exception e) {
            this.update(Cycle.ERROR, null, e); //发生异常时触发的方法
        }
    }

    //定义的监控者实现 监控者根据状态变化采取的行动
    private final TaskLifeCycle<T> lifeCycle;

    //返回值
    private final TaskFuture<T> task;

    //状态
    private Cycle cycle;

    public OneConsumer(TaskLifeCycle<T> lifeCycle, TaskFuture<T> task) {
        //Thread的构造方法
        super();
        if (task == null)
            throw new IllegalArgumentException("Task is not allowed for null");
        this.lifeCycle = lifeCycle;
        this.task = task;
    }

    @Override
    public Cycle getCycle() {
        return null;
    }

    @Override
    public void start() {

    }

    @Override
    public void interrupt() {

    }

    //更新状态
    private void update(Cycle cycle, T result, Exception e) {
        this.cycle = cycle;
        if (lifeCycle == null) {
            return;
        }
        try {
            switch (cycle) {
                case STARTED:
                    this.lifeCycle.onStart(currentThread());
                    break;
                case RUNNING:
                    this.lifeCycle.onRunning(currentThread());
                    break;
                case DONE:
                    this.lifeCycle.onFinish(currentThread(), result);
                    break;
                case ERROR:
                    this.lifeCycle.onError(currentThread(), e);
                    break;
            }
        } catch (Exception ex) {
            if (cycle == Cycle.ERROR) {
                throw ex;
            }
        }
    }
}
